package thinkingInJava.concurrency;

//: concurrency/Joining.java
//Understanding join().
//http://macleo.iteye.com/blog/626283
//Sleeper是一个会睡上一段时间的Thread，至于睡多长时间，这要由构造函数的参数决定。Sleeper的run( )的sleep( )可以因时限到期而返回，也可以被interrupt( )打断。catch语句在报告中断的同时，会一并报告isInterrupted( )。当有别的线程调用了本线程的interrupt( )时，会设置一个标记以表示这个这个线程被打断了。当本线程捕获这个异常的时候，会清除这个标志。所以catch语句会永远报告说isInterrupted( )是false。这个标记是用来应付其它情况的，或许在没出异常的情况下，线程要用它来检查自己是不是被中断了。  
//Joiner是另一个线程，它调用了Sleeper的join( )，所以它要等Sleeper醒过来。main( )创建了两个Sleeper分派给两个Joiner。你会发现，不论Sleeper是被打断还是正常结束，Joiner都会随Sleeper一道结束。
import static thinkingInJava.YTool.YPrint.*;

class Sleeper extends Thread {
	private int duration;
	public Sleeper(String name, int sleepTime) {
		super(name);
		duration = sleepTime;
		start();
	}
	public void run() {
		try {
			sleep(duration);
		} catch(InterruptedException e) {
			print(getName() + " was interrupted. " +
					"isInterrupted(): " + isInterrupted());
			return;
		}
		print(getName() + " has awakened");
	}
}

class Joiner extends Thread {
	private Sleeper sleeper;
	public Joiner(String name, Sleeper sleeper) {
		super(name);
		this.sleeper = sleeper;
		start();
	}
	public void run() {
		try {
			sleeper.join(); // 当前线程等 sleeper 执行完了(或中断了)才开始执行
		} catch(InterruptedException e) {
			print("Interrupted");
		}
		print(getName() + " join completed");
	}
}

public class Joining {
	public static void main(String[] args) {
		Sleeper
		sleepy = new Sleeper("Sleepy", 1500),
		grumpy = new Sleeper("Grumpy", 1500);
		Joiner
		dopey = new Joiner("Dopey", sleepy),
		doc = new Joiner("Doc", grumpy);
		grumpy.interrupt();
	}
} /* Output:
Grumpy was interrupted. isInterrupted(): false
Doc join completed
Sleepy has awakened
Dopey join completed
 *///:~
